/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package map;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;

/**
 *
 * @author victorinox
 */
public class GoogleMaps {

    String apiKey = "ABQIAAAAogSIWIfVmFCOD-rErmvTpRRg41wGbOdL4b9-7ehhQsy4EhQckBR0cfTZ_GgX7qdOcqEUtBfoK7dCzg";
    
    public GoogleMaps() {
    }

    public String[] geocodeAddress(String address) throws Exception {
        byte[] res = loadHttpFile(getGeocodeUrl(address));

        String resString = new String(res, 0, res.length);

        String[] data = split(resString, ',');

        if (data[0].compareTo("200") != 0) {
            int errorCode = Integer.parseInt(data[0]);

            throw new Exception("Erro ao visualizar mapa: " + getGeocodeError(errorCode));
        } else {
            return new String[]{ data[2], data[3] };
        }
    }

    public Image retrieveStaticImage(int width, int height, String lat, String lng, int zoom, String format) throws Exception {

        return loadHttpFileImage(getMapUrl(width, height, lng, lat, zoom, format));

    }

    private String getGeocodeError(int errorCode) {
        String err = "";
        switch (errorCode) {
            case 400:
                err = "Requisição errada";
                break;
            case 500:
                err = "Erro no servidor";
                break;
            case 601:
                err = "Consulta não existe";
                break;
            case 602:
                err = "Endereco invalido";
                break;
            case 603:
                err = "Enderecao não encontrado";
                break;
            case 604:
                err = "Direcoes não encontradas";
                break;
            case 610:
                err = "Erro na chave de ativação do mapa";
                break;
            case 620:
                err = "Muitas consultas";
                break;
            default:
                err = "Erro desconhecido";
                break;
        }
        return err += ". Contate o suporte do fabricante do software.";
    }

    String getGeocodeUrl(String address) {
        return "http://maps.google.com/maps/geo?q=" + urlEncode(address) + "&output=csv&key=" + apiKey;
    }

    String getMapUrl(int width, int height, String lng, String lat, int zoom, String format) {

        return "http://maps.google.com/staticmap?center=" +
                lat + "," + lng + "&format=" + format + "&zoom=" + zoom + "&size=" +
                width + "x" + height + "&key=" + apiKey + "&sensor=&maptype=mobile" +
                "&markers=" + lat + "," + lng;
        
    }

    String urlEncode(String str) {
        StringBuffer buf = new StringBuffer();
        char c;
        for (int i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            if ((c >= '0' && c <= '9') ||
                    (c >= 'A' && c <= 'Z') ||
                    (c >= 'a' && c <= 'z')) {
                buf.append(c);
            } else {
                buf.append("%").append(Integer.toHexString((int) str.charAt(i)));
            }
        }
        return buf.toString();
    }

    byte[] loadHttpFile(String url) throws Exception {

        HttpConnection hc = null;

        InputStream is = null;

        byte[] byteBuffer = null;

        try {
            hc = (HttpConnection) Connector.open(url);

            hc.setRequestMethod(HttpConnection.GET);

            int ch;

            is = hc.openInputStream();

            int len = (int) hc.getLength();

            if (len > 0) {
                byteBuffer = new byte[len];

                is.read(byteBuffer);
            } else {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                while ((ch = is.read()) != -1) {
                    bos.write(ch);
                }
                byteBuffer = bos.toByteArray();

                bos.close();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (hc != null) {
                    hc.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return byteBuffer;
    }

    private Image loadHttpFileImage(String url) throws Exception {

        HttpConnection hc = null;

        InputStream is = null;

        try {
            hc = (HttpConnection) Connector.open(url);

            hc.setRequestMethod(HttpConnection.GET);

            is = hc.openInputStream();

            return Image.createImage(is);

        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (hc != null) {
                    hc.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    static String[] split(String s, int chr) {
        Vector res = new Vector();

        int curr = 0;
        int prev = 0;

        while ((curr = s.indexOf(chr, prev)) >= 0) {
            res.addElement(s.substring(prev, curr));

            prev = curr + 1;
        }
        res.addElement(s.substring(prev));

        String[] splitted = new String[res.size()];

        res.copyInto(splitted);

        return splitted;
    }
}
